//
//  HDPreviewViewController.swift
//  HuaDaoPeifu
//
//  Created by Apple on 2018/6/19.
//  Copyright © 2018年 paiyipai. All rights reserved.
//

import Foundation
import SVProgressHUD

class HDPreviewViewController: UIViewController {
    
    var info_id = ""
    var case_id = ""

    @IBOutlet weak var nameLB: UILabel!
    @IBOutlet weak var relationLB: UILabel!
    @IBOutlet weak var identifierTypeLB: UILabel!
    @IBOutlet weak var genderLB: UILabel!
    @IBOutlet weak var critcodeLB: UILabel!
    @IBOutlet weak var phoneLB: UILabel!
    @IBOutlet weak var jobLB: UILabel!
    @IBOutlet weak var addressLB: UILabel!
    @IBOutlet weak var emailLB: UILabel!
    @IBOutlet weak var accountNameLB: UILabel!
    @IBOutlet weak var accountnoLB: UILabel!
    @IBOutlet weak var banknameLB: UILabel!
    @IBOutlet weak var subbanknameLB: UILabel!
    
    @IBOutlet weak var claimtypeLB: UILabel!
    @IBOutlet weak var claimtimeLB: UILabel!
    @IBOutlet weak var hospitalLB: UILabel!
    @IBOutlet weak var totalmoneyLB: UILabel!
    @IBOutlet weak var diseaseLB: UILabel!
    @IBOutlet weak var claimAddressLB: UILabel!
    @IBOutlet weak var createTimeLB: UILabel!
    
    var accidentProcessLB: UILabel!
    var accidentProcessTitleLB: UILabel!
    
    @IBOutlet weak var standardTitleLB: UILabel!
    @IBOutlet weak var relationViewHeightConstrant: NSLayoutConstraint!
    
    @IBOutlet weak var identifierHightConstraint: NSLayoutConstraint!
    @IBOutlet weak var bottomMarginConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var identifierView: UIView!
    
    @IBOutlet weak var relationView: UIView!
    
    @IBOutlet weak var scrollerView: UIScrollView!
    
    @IBOutlet weak var View2: UIView!
    @IBOutlet weak var View1: UIView!
    fileprivate var View4 = HDPreCollectionView()
    
    let manager1: HXPhotoManager = HXPhotoManager(type: HXPhotoManagerSelectedTypePhoto)
    let toolManager1: HXDatePhotoToolManager = HXDatePhotoToolManager.init()
    var photoView1: HXPhotoView?
    
    let manager2: HXPhotoManager = HXPhotoManager(type: HXPhotoManagerSelectedTypePhoto)
    let toolManager2: HXDatePhotoToolManager = HXDatePhotoToolManager.init()
    var photoView2: HXPhotoView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupUI()
        loadData()
    }
    
    func setupUI() {
        self.navigationItem.title = "理赔申请表预览"
        self.View1.layer.shadowOffset = CGSize(width: 1, height: 4)
        self.View1.layer.shadowColor = UIColor.lightGray.cgColor
        self.View1.layer.shadowOpacity = 0.4
        self.View1.layer.cornerRadius = 3
        
        self.View2.layer.shadowOffset = CGSize(width: 1, height: 4)
        self.View2.layer.shadowColor = UIColor.lightGray.cgColor
        self.View2.layer.shadowOpacity = 0.4
        self.View2.layer.cornerRadius = 3
        
        // 设置两个photoview
        photoView1 = HXPhotoView(frame: CGRect(x: (AppConstant.screenWidth-300)*0.5, y: 56, width: 300, height: 0), manager: manager1)
        identifierView.addSubview(photoView1!)
        photoView1?.delegate = self

        photoView1?.showAddCell = false
        photoView1?.hideDeleteButton = true
        photoView1?.editEnabled = false
        photoView1?.manager.configuration.photoCanEdit = false
        photoView1?.previewShowDeleteButton = false
        
        photoView2 = HXPhotoView(frame: CGRect(x: (AppConstant.screenWidth-300)*0.5, y: 56, width: 300, height: 0), manager: manager2)
        relationView.addSubview(photoView2!)
        photoView2?.delegate = self
        
        photoView2?.showAddCell = false
        photoView2?.hideDeleteButton = true
        photoView2?.editEnabled = false
        photoView2?.manager.configuration.photoCanEdit = false
        photoView2?.previewShowDeleteButton = false
    }
    
    fileprivate func loadData() {
        HDApiManagerHandler.requestApplicationForm(info_id, case_id) {[unowned self] (model) in
            guard let model = model else {
                SVProgressHUD.showError("未查询到有效信息...")
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                    self.navigationController?.popViewController(animated: true)

                })
                // 获取数据失败
                return
            }
            
            self.bindData(model)
        }
    }
    
    fileprivate func bindData(_ formData:HDApplicationFormModel) {
        nameLB.text = formData.name
        relationLB.text = formData.relation == "0" ? "本人" : "子女"
        // 显示子女附件
        if formData.relation == "0" {
            relationViewHeightConstrant.constant = 0
            relationView.isHidden = true
        }else {
            loadArvchiveImages(formData.born_id, photoView2, relationViewHeightConstrant)
        }
        
        identifierTypeLB.text = getIDTypeName(IDNumber: formData.crittype)
        critcodeLB.text = formData.critcode
        phoneLB.text = formData.phone
        jobLB.text = formData.job
        addressLB.text = formData.address
        emailLB.text = formData.email
        accountNameLB.text = formData.account_name
        accountnoLB.text = formData.accountno
        banknameLB.text = formData.bank
        subbanknameLB.text = formData.subBranch
        
        claimtypeLB.text = formData.claim_type == "1" ? "疾病" : "意外"
        // 显示事件经过
        if formData.claim_type == "2" {
            setupProcessPart(formData.accident_process)
        }
        
        claimtimeLB.text = formData.claim_time
        hospitalLB.text = formData.hospital
        diseaseLB.text = formData.disease
        totalmoneyLB.text = formData.total_money
        claimAddressLB.text = formData.claim_address
        createTimeLB.text = formData.created
        
        loadArvchiveImages(formData.images, photoView1, identifierHightConstraint)
        
    }
    
    fileprivate func loadArvchiveImages (_ url:String, _ photoView:HXPhotoView?,_ heightConstraint:NSLayoutConstraint) {
        var urlStrings = [String]()
        for urlSubString in url.split(separator: ",") {
            if urlSubString.first == "."{
                if urlSubString.startIndex != Substring.Index.init(encodedOffset: 0){
                    continue
                }
                urlStrings.append(kBaseApiv2URL + "/picc" + urlSubString.substring(from: urlSubString.index(urlSubString.startIndex, offsetBy: 2)))
            }else{
                urlStrings.append(kBaseApiv2URL + urlSubString.description)
            }
        }
        setArchiveImageUrl(urlStrings, photoView)
        
    }
    
    fileprivate func setupProcessPart(_ accident_process: String) {
        accidentProcessTitleLB = UILabel(frame: standardTitleLB.frame)
        View2.addSubview(accidentProcessTitleLB)
        accidentProcessLB = UILabel(frame: accidentProcessTitleLB.frame)
        View2.addSubview(accidentProcessLB)
        accidentProcessTitleLB.text = "事故经过:"
        accidentProcessTitleLB.font = standardTitleLB.font
        accidentProcessTitleLB.textColor = standardTitleLB.textColor
        
        accidentProcessLB.text = accident_process
        accidentProcessLB.numberOfLines = 0
        accidentProcessLB.textColor = createTimeLB.textColor
        accidentProcessLB.font = createTimeLB.font
        
        // 移除旧约束
        View2.removeConstraint(bottomMarginConstraint)
        
        accidentProcessTitleLB.snp.makeConstraints { (make) in
            make.leading.height.equalTo(standardTitleLB)
            make.top.equalTo(standardTitleLB.snp.bottom).offset(10)
        }
        
        accidentProcessLB.snp.makeConstraints { (make) in
            make.leading.equalTo(createTimeLB)
            make.top.equalTo(accidentProcessTitleLB)
            //            make.firstBaseline.equalTo(accidentProcessTitleLB)
            make.right.equalTo(View2).offset(-10)
            make.height.greaterThanOrEqualTo(21)
            make.bottom.equalTo(View2).offset(-10)
        }
    }
    
    /// 加载网络图片，并刷新
    func setArchiveImageUrl (_ urls:[String],_ photoView:HXPhotoView?) {
        photoView?.manager.addNetworkingImage(toAlbum: urls, selected: true)
        photoView?.refreshView()
    }
    
    func setupImageView(_ urlStrings : [String],_ superView : UIView) -> CGFloat {
        
        let imgW : CGFloat = 100
        let imgH : CGFloat = 100
        let colCount = 3
        let margin = (AppConstant.screenWidth - CGFloat(colCount) * imgW)/CGFloat(colCount + 1)
        let topMargin : CGFloat = 10
        if urlStrings.count > 0 {
            for i in 0..<urlStrings.count {
                let row = i / colCount
                let col = i % colCount
                let x = margin + (imgW + margin) * CGFloat(col)
                let y = 46.0 + topMargin + (imgH + topMargin) * CGFloat(row)
                
                let iv = UIImageView(frame: CGRect(x: x, y: y, width: imgW, height: imgH))
                superView.addSubview(iv)
                
                iv.sd_setImage(with: URL(string: urlStrings[i])) { (image, error, cache, url) in
                    
                }
                
            }
            
            let rowCount = ceil(CGFloat(urlStrings.count) / CGFloat(colCount))
            let height = (imgH + topMargin) * CGFloat(rowCount) + topMargin + 46.0
            return height
        }else{
            return 0
        }
    }
    
    // 根据ID返回身份类型
    fileprivate func getIDTypeName(IDNumber:String) -> String  {
        if IDNumber == "0" {
            return "身份证"
        }else if IDNumber == "1" {
            return "护照"
        }else if IDNumber == "7" {
            return "出生证"
        }else if IDNumber == "11" {
            return "回乡证"
        }else if IDNumber == "8-1" {
            return "驾驶证"
        }else if IDNumber == "9" {
            return "工号"
        }else if IDNumber == "8-2" {
            return "港澳通行证"
        }else if IDNumber == "4" {
            return "户口本"
        }else if IDNumber == "2" {
            return "军官证"
        }else {
            return "台湾通行证"
        }
    }
}

extension HDPreviewViewController :HXPhotoViewDelegate{
    func photoView(_ photoView: HXPhotoView!, updateFrame frame: CGRect) {
        
        if photoView == photoView1 {
            if frame.size.height == (identifierHightConstraint.constant - 56.0 - 10.0) {
                return
            }
            
            // 更新高度约束
            identifierHightConstraint.constant = frame.height + 56 + 10.0
            return
        }
        
        if photoView == photoView2 {
            if frame.size.height == (relationViewHeightConstrant.constant - 56.0 - 10.0) {
                return
            }
            
            // 更新高度约束
            relationViewHeightConstrant.constant = frame.height + 56 + 10.0
            return
        }
    }
    
    func photoView(_ photoView: HXPhotoView!, changeComplete allList: [HXPhotoModel]!, photos: [HXPhotoModel]!, videos: [HXPhotoModel]!, original isOriginal: Bool) {
       
    }
}
